/**
 * 完整的弹幕演示组件
 * 包含所有UI和功能，可以直接在任何项目中使用
 * 无需额外配置，开箱即用
 */

import React, { useRef, useState, useCallback, useEffect } from 'react'
import { 
  VideoBarrage, 
  useBarrage, 
  createBarrage, 
  getPreset,
  getRandomColor,
  // ApiManager,
  // BarrageAPI,
  useVideoManager,
  VideoDrawer
} from './index'
import type { BarrageData } from './index'

// 内联样式，避免外部CSS依赖
const styles = {
  app: {
    fontFamily: 'Arial, sans-serif',
    maxWidth: '1200px',
    margin: '0 auto',
    padding: '20px',
    backgroundColor: '#f5f5f5',
    minHeight: '100vh'
  } as React.CSSProperties,
  
  title: {
    textAlign: 'center' as const,
    color: '#333',
    marginBottom: '30px',
    fontSize: '28px',
    fontWeight: 'bold'
  } as React.CSSProperties,
  
  videoContainer: {
    position: 'relative' as const,
    width: '100%',
    height: '600px',
    backgroundColor: '#000',
    borderRadius: '8px',
    overflow: 'hidden',
    marginBottom: '20px',
    boxShadow: '0 4px 12px rgba(0,0,0,0.15)'
  } as React.CSSProperties,
  
  video: {
    width: '100%',
    height: '100%',
    objectFit: 'contain' as const
  } as React.CSSProperties,
  
  controls: {
    backgroundColor: '#fff',
    padding: '20px',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
    marginBottom: '20px'
  } as React.CSSProperties,
  
  inputSection: {
    display: 'flex',
    gap: '10px',
    marginBottom: '15px',
    alignItems: 'center'
  } as React.CSSProperties,
  
  input: {
    flex: 1,
    padding: '12px',
    border: '2px solid #e1e5e9',
    borderRadius: '6px',
    fontSize: '14px',
    outline: 'none',
    transition: 'border-color 0.2s'
  } as React.CSSProperties,
  
  button: {
    padding: '12px 20px',
    border: 'none',
    borderRadius: '6px',
    fontSize: '14px',
    fontWeight: '500',
    cursor: 'pointer',
    transition: 'all 0.2s',
    outline: 'none'
  } as React.CSSProperties,
  
  primaryButton: {
    backgroundColor: '#007bff',
    color: 'white'
  } as React.CSSProperties,
  
  secondaryButton: {
    backgroundColor: '#6c757d',
    color: 'white'
  } as React.CSSProperties,
  
  dangerButton: {
    backgroundColor: '#dc3545',
    color: 'white'
  } as React.CSSProperties,
  
  successButton: {
    backgroundColor: '#28a745',
    color: 'white'
  } as React.CSSProperties,
  
  controlButtons: {
    display: 'flex',
    gap: '10px',
    flexWrap: 'wrap' as const,
    marginBottom: '15px'
  } as React.CSSProperties,
  
  statusInfo: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))',
    gap: '10px',
    fontSize: '12px',
    color: '#666'
  } as React.CSSProperties,
  
  statusItem: {
    padding: '8px 12px',
    backgroundColor: '#f8f9fa',
    borderRadius: '4px',
    textAlign: 'center' as const
  } as React.CSSProperties,
  
  serverOnline: {
    color: '#28a745'
  } as React.CSSProperties,
  
  serverOffline: {
    color: '#dc3545'
  } as React.CSSProperties,
  
  features: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
    gap: '15px',
    marginTop: '20px'
  } as React.CSSProperties,
  
  featureCard: {
    backgroundColor: '#fff',
    padding: '20px',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
  } as React.CSSProperties,
  
  featureTitle: {
    fontSize: '16px',
    fontWeight: 'bold',
    marginBottom: '10px',
    color: '#333'
  } as React.CSSProperties,
  
  featureList: {
    listStyle: 'none',
    padding: 0,
    margin: 0
  } as React.CSSProperties,
  
  featureItem: {
    padding: '4px 0',
    fontSize: '14px',
    color: '#666'
  } as React.CSSProperties
}

/**
 * 完整的弹幕演示应用组件
 * 可以直接导入到任何React项目中使用
 */
export const BarrageDemoApp: React.FC = () => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const [inputText, setInputText] = useState('')
  // const [queueStatus, setQueueStatus] = useState({ queueLength: 0, activeCount: 0, maxCount: 0 })
  
  // 弹幕数据状态
  // const [allBarrageData, setAllBarrageData] = useState<BarrageData[]>([])
  const [barrageData, setBarrageData] = useState<BarrageData[]>([])
  const [displayedBarrages, setDisplayedBarrages] = useState<Set<string>>(new Set())
  // const [serverStatus, setServerStatus] = useState<'connected' | 'disconnected' | 'checking'>('checking')
  // const [syncStatus, setSyncStatus] = useState<'synced' | 'syncing' | 'paused'>('synced')
  
  // 保留一些必要的状态
  const [detectionMode] = useState(true)
  const [showSkeleton, setShowSkeleton] = useState(false)
  // const [poseState, setPoseState] = useState<PoseDetectionState>({
  //   initialized: false,
  //   initializing: false,
  //   modelLoaded: false,
  //   runningMode: 'VIDEO',
  // })

  // 视频管理
  const {
    videos,
    currentVideoId,
    selectVideo,
    uploadVideo,
    refreshVideos
  } = useVideoManager({
    onVideoChange: (video) => {
      if (videoRef.current) {
        videoRef.current.src = video.url
        videoRef.current.load()
      }
      
      if (barrageRef.current) {
        barrageRef.current.clear()
        
        if ('clearCanvas' in barrageRef.current) {
          (barrageRef.current as any).clearCanvas()
          setTimeout(() => {
            if (barrageRef.current && 'clearCanvas' in barrageRef.current) {
              (barrageRef.current as any).clearCanvas()
            }
          }, 50)
        }
      }
      
      setTimeout(() => {
        if (barrageRef.current && 'setupCanvas' in barrageRef.current) {
          (barrageRef.current as any).setupCanvas()
        }
      }, 100)
    }
  })

  const [isVideoDrawerOpen, setIsVideoDrawerOpen] = useState(false)

  // 使用弹幕Hook
  const {
    barrageRef,
    addBarrage,
    // clearBarrages,
    // activeCount,
    // maxCapacity,
    isFull
  } = useBarrage({
    config: getPreset('default'),
    events: {}
  })

  // 初始化
  useEffect(() => {
    // 可以在这里设置API地址
    // setApiBaseUrl('http://localhost:3001')
    
    // 加载演示弹幕数据
    const loadDemoBarrages = () => {
      const demoBarrages = [
        { id: '1', text: '欢迎使用弹幕系统！', time: 5, color: '#FFD700', videoId: 'demo' },
        { id: '2', text: '支持人体检测避让', time: 10, color: '#4ECDC4', videoId: 'demo' },
        { id: '3', text: '高性能Canvas渲染', time: 15, color: '#FF6B6B', videoId: 'demo' },
        { id: '4', text: '完全自包含组件', time: 20, color: '#A8E6CF', videoId: 'demo' },
      ]
      // setAllBarrageData(demoBarrages as BarrageData[])
      setBarrageData(demoBarrages as BarrageData[])
    }
    
    loadDemoBarrages()
  }, [])

  // 发送弹幕
  const handleSendBarrage = async () => {
    if (!inputText.trim() || isFull) return

    const barrage = createBarrage(inputText, {
      color: getRandomColor(),
      fontSize: 20,
      user: '用户' + Math.floor(Math.random() * 1000)
    })
    
    addBarrage(barrage)
    setInputText('')
  }

  // 压力测试
  const handleStressTest = useCallback(() => {
    if (!videoRef.current) return
    
    // const videoDuration = videoRef.current.duration || 30
    // const testBarrages: any[] = []
    
    for (let i = 0; i < 100; i++) {
      // const time = Math.random() * videoDuration
      const barrage = createBarrage(`压力测试弹幕 ${i + 1}`, {
        color: getRandomColor(),
        fontSize: 18 + Math.random() * 8,
        user: `测试用户${i + 1}`
      })
      
      setTimeout(() => addBarrage(barrage), i * 50)
    }
  }, [addBarrage])

  // 切换检测模式
  // const toggleDetectionMode = () => {
  //   setDetectionMode(!detectionMode)
  // }

  // 定期更新队列状态
  useEffect(() => {
    const updateQueueStatus = () => {
      if (barrageRef.current && 'getQueueStatus' in barrageRef.current) {
        // const status = (barrageRef.current as any).getQueueStatus()
        // setQueueStatus(status)
      }
    }

    const interval = setInterval(updateQueueStatus, 1000)
    return () => clearInterval(interval)
  }, [])

  // 视频时间监听 - 自动显示弹幕
  useEffect(() => {
    const video = videoRef.current
    if (!video || barrageData.length === 0) return

    const displayedBarragesRef = { current: displayedBarrages }
    displayedBarragesRef.current = displayedBarrages

    const handleTimeUpdate = () => {
      const currentTime = video.currentTime
      
      const currentBarrages = barrageData.filter(barrage => {
        const timeDiff = Math.abs(barrage.time - currentTime)
        const isInTimeRange = timeDiff < 0.5
        const notDisplayed = !displayedBarragesRef.current.has(barrage.id || '')
        return isInTimeRange && notDisplayed
      })

      currentBarrages.forEach(barrageItem => {
        const barrage = createBarrage(barrageItem.text, {
          color: barrageItem.color,
          fontSize: 20
        })
        addBarrage(barrage)
        
        setDisplayedBarrages(prev => new Set([...prev, barrageItem.id || '']))
      })
    }

    video.addEventListener('timeupdate', handleTimeUpdate)
    
    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate)
    }
  }, [barrageData, addBarrage, displayedBarrages])

  return (
    <div style={styles.app}>
      <h1 style={styles.title}>🎯 弹幕系统演示</h1>
      
      {/* 视频容器 */}
      <div style={styles.videoContainer}>
        <video
          ref={videoRef}
          src="/demo-video.mp4"
          controls
          style={styles.video}
        />
        
        {/* 弹幕组件 */}
        <VideoBarrage
          ref={barrageRef}
          videoRef={videoRef}
          config={{
            ...getPreset('default'),
            faceDetection: detectionMode,
            showSkeleton: showSkeleton
          }}
          enabled={true}
        />
      </div>
      
      {/* 控制面板 */}
      <div style={styles.controls}>
        {/* 弹幕输入 */}
        <div style={styles.inputSection}>
          <input
            type="text"
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSendBarrage()}
            placeholder="输入弹幕内容..."
            style={{
              ...styles.input,
              borderColor: inputText ? '#007bff' : '#e1e5e9'
            }}
            disabled={isFull}
          />
          <button 
            onClick={handleSendBarrage}
            style={{
              ...styles.button,
              ...styles.primaryButton,
              opacity: (!inputText.trim() || isFull) ? 0.5 : 1,
              cursor: (!inputText.trim() || isFull) ? 'not-allowed' : 'pointer'
            }}
            disabled={!inputText.trim() || isFull}
          >
            发送弹幕
          </button>
        </div>
        
        {/* 控制按钮 */}
        <div style={styles.controlButtons}>
          <button 
            onClick={() => setShowSkeleton(!showSkeleton)}
            style={{
              ...styles.button,
              backgroundColor: showSkeleton ? '#17a2b8' : '#6c757d',
              color: 'white'
            }}
            disabled={!detectionMode}
            title={showSkeleton ? '隐藏骨架线' : '显示骨架线'}
          >
            {showSkeleton ? '🦴 骨架显示' : '🦴 骨架隐藏'}
          </button>
          <button 
            onClick={() => setIsVideoDrawerOpen(true)}
            style={{...styles.button, ...styles.successButton}}
          >
            📁 视频库
          </button>
          <button 
            onClick={handleStressTest}
            style={{...styles.button, ...styles.dangerButton}}
            title="生成100条弹幕进行压力测试"
          >
            🔬 压力测试
          </button>
        </div>
        
        {isFull && (
          <div style={{
            marginTop: '10px',
            padding: '10px',
            backgroundColor: '#fff3cd',
            border: '1px solid #ffeaa7',
            borderRadius: '4px',
            color: '#856404',
            textAlign: 'center'
          }}>
            ⚠️ 弹幕容量已满，请等待或清空弹幕
          </div>
        )}
      </div>
      
      {/* 功能特性展示 */}
      <div style={styles.features}>
        <div style={styles.featureCard}>
          <div style={styles.featureTitle}>🚀 核心功能</div>
          <ul style={styles.featureList}>
            <li style={styles.featureItem}>✅ 高性能Canvas渲染</li>
            <li style={styles.featureItem}>✅ MediaPipe人体检测</li>
            <li style={styles.featureItem}>✅ 智能弹幕避让</li>
            <li style={styles.featureItem}>✅ 多种弹幕样式</li>
            <li style={styles.featureItem}>✅ 响应式适配</li>
          </ul>
        </div>
        
        <div style={styles.featureCard}>
          <div style={styles.featureTitle}>🎨 使用特性</div>
          <ul style={styles.featureList}>
            <li style={styles.featureItem}>✅ 完全自包含</li>
            <li style={styles.featureItem}>✅ 无需额外配置</li>
            <li style={styles.featureItem}>✅ 开箱即用</li>
            <li style={styles.featureItem}>✅ TypeScript支持</li>
            <li style={styles.featureItem}>✅ 内联样式</li>
          </ul>
        </div>
        
        <div style={styles.featureCard}>
          <div style={styles.featureTitle}>🔧 技术栈</div>
          <ul style={styles.featureList}>
            <li style={styles.featureItem}>⚡ React + TypeScript</li>
            <li style={styles.featureItem}>🎯 Canvas 2D渲染</li>
            <li style={styles.featureItem}>🤖 MediaPipe AI</li>
            <li style={styles.featureItem}>🎪 Fly-Barrage引擎</li>
            <li style={styles.featureItem}>📡 RESTful API</li>
          </ul>
        </div>
      </div>
      
      {/* 视频抽屉 */}
      <VideoDrawer
        videos={videos}
        currentVideoId={currentVideoId}
        onVideoSelect={selectVideo}
        onVideoUpload={async (file) => {
          try {
            await uploadVideo(file)
          } catch (error) {
            alert(`视频上传失败: ${error instanceof Error ? error.message : '未知错误'}`)
          }
        }}
        onRefresh={refreshVideos}
        isOpen={isVideoDrawerOpen}
        onClose={() => setIsVideoDrawerOpen(false)}
      />
    </div>
  )
}

// 默认导出
export default BarrageDemoApp
